#!/bin/sh

. "$(dirname $0)/test-lib.sh"

# This test checks if virsh obeys the proper precedence of different
# URI settings
test_intro "virsh-uriprecedence"

virsh_bin="$abs_top_builddir/tools/virsh"
virsh_cmd="$virsh_bin"
counter=0
ret=0

mock_xdg_ || framework_failure

is_uri_good()
{
    echo "$1" | grep -q -F "$good_uri"
}

test_uri_internal()
{
    test_name=$1
    test_cmd="$virsh_cmd \"$2\""
    result=0

    debug "Running '$test_cmd'"
    out="$($virsh_cmd "$2")"

    if ! is_uri_good "$out"; then
        debug "Invalid output: '$out'"
        result=1
        ret=1
    fi

    counter="$((counter+1))"
    test_result "$counter" "$1" "$result"
}

test_uri_connect()
{
    test_uri_internal "$1" "connect; uri"
}

test_uri_noconnect()
{
    test_uri_internal "$1" "uri"
}

test_uri()
{
    test_uri_connect "$1"
    test_uri_noconnect "$1"
}

# Precedence is the following (lowest priority first):
#
# 1) if run as root, 'uri_default' from /etc/libvirtd/libvirt.conf,
#    otherwise qemu:///session.  There is no way to mock this file for
#    virsh/libvirt.so and the user may have set anything in there that
#    would spoil the test, so we don't test this
#
# 2) 'uri_default' from $XDG_CONFIG_HOME/libvirt/libvirt.conf
#
# 3) LIBVIRT_DEFAULT_URI
#
# 4) VIRSH_DEFAULT_CONNECT_URI
#
# 5) parameter -c (--connect)

unset LIBVIRT_DEFAULT_URI
unset VIRSH_DEFAULT_CONNECT_URI
bad_uri="test:///default?bad_uri"
good_uri="test:///default?good_uri"

printf "uri_default=\"%s\"\n" "$good_uri" >"$XDG_CONFIG_HOME/libvirt/libvirt.conf"
if uid_is_privileged_; then
    counter="$((counter+1))"
    test_skip_case "$counter" "User config file" "must not be run as root"
else
    test_uri "User config file"
fi

printf "uri_default=\"%s\"\n" "$bad_uri" >"$XDG_CONFIG_HOME/libvirt/libvirt.conf"
export LIBVIRT_DEFAULT_URI="$good_uri"
test_uri "LIBVIRT_DEFAULT_URI"

export LIBVIRT_DEFAULT_URI="$bad_uri"
export VIRSH_DEFAULT_CONNECT_URI="$good_uri"
test_uri "VIRSH_DEFAULT_CONNECT_URI"

export VIRSH_DEFAULT_CONNECT_URI="$bad_uri"
virsh_cmd="$virsh_bin --connect $good_uri"
test_uri "Parameter"

test_final "$counter" "$ret"
(exit "$ret"); exit "$ret"
